<template>
	<view class="body">
		<view class="first-box">
			<uni-section class="dateTitle" title="选择预约地址" type="line" titleFontSize="20px">
			</uni-section>
			<view class="address-box">
				<view :class="['address-list', {'color-add': activeIndex1 === i}, {'color-default': activeIndex1 !== i}]" 
				v-for="(item, i) in addressList" :key="i" @click="clickHandler1(i)">
					<view class="">{{item.addressTitle}}</view>
					<view class="addressDetail">{{item.address}}</view>
				</view>
				
			</view>
		</view>
		<view class="second-box">
			<uni-section class="dateTitle" title="选择入馆日期" type="line" titleFontSize="20px">
				{{new Date().getMonth() + 1}}月
			</uni-section>
			<view class="calendar-box">
				<view class="days-box" >
					<view class="" v-for="(item, i) in days" :key="index">{{item}}</view>
				</view>
				<view class="tickets-box">
					<view :class="['ticket-inner-box', {'color-add': activeIndex2 === i}, {'color-default': activeIndex2 !== i}]" 
					v-for="(item, i) in dateList" :key="i" :style="{width: ((ww - 40) /7) + 'px'}" @click="clickHandler2(i)">
						<!-- <view class="">{{ new Date().getDate()}}</view> -->
						<view class="">{{ item.day }}</view>
						<view class="">{{ item.hasTicket }}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="third-box">
			<uni-section class="dateTitle" title="选择入馆时段" type="line" titleFontSize="20px">
			</uni-section>
			<view class="time-between" v-if="getDayOfWeek() !== 1">
				<!-- <block v-if="showIndex === 0"> -->
				<block>
					<view :class="['time-between-list', 
					{'color-add': activeIndex3 === i && (new Date(ticketList1[activeIndex3].exhibitionEndTime).getTime() - new Date().getTime()) > 0}, 
					{'color-default': activeIndex3 !== i }]"
					v-for="(item, i) in ticketList1" :key="i" @click="clickHandler3(i)" >
						<view class="">{{item.exhibitionBeginTime.split(' ')[1] + '-' + item.exhibitionEndTime.split(' ')[1]}}</view>
						<view class="count">余{{item.remainQuantity}}</view>
					</view>
				</block>
				<!-- <block v-else>
					<view :class="['time-between-list', 
					{'color-add': activeIndex3 === i && (new Date(ticketList1[activeIndex3].exhibitionEndTime).getTime() - new Date().getTime()) > 0}, 
					{'color-default': activeIndex3 !== i }]"
					v-for="(item, i) in ticketList1" :key="i" @click="clickHandler4(i)"
					v-if="(new Date(ticketList1[activeIndex3].exhibitionEndTime).getTime() - new Date().getTime()) > 0">
						<view class="">{{item.exhibitionBeginTime.split(' ')[1] + '-' + item.exhibitionEndTime.split(' ')[1]}}</view>
						<view class="count">余{{item.remainQuantity}}</view>
					</view>
				</block> -->
				
			</view>
		</view>
		
		<view class="commit-btn-box">
			<button type="primary" class="commit-btn" @click="bookTicket">预约门票</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//系统属性
				sysInfo: {},
				//手机屏幕高度
				wh: 0,
				//手机屏幕宽度
				ww: 0,
				days: ['日','一', '二', '三', '四', '五', '六'],
				//博物馆地址列表
				addressList: [
					{
						addressTitle: '博物馆区预约',
						address: '大学城华师一路八号'
					},
					{
						addressTitle: '康陵遗址预约',
						address: '大学城康陵路'
					}
				],
				//日期列表
				dateList: [],
				//时间段列表
				timeList: [
					{
						time: '09:00-12:00',
						remain: '1500'
					},
					{
						time: '12:00-17:00',
						remain: '1500'
					}
				],
				//是否有票列表
				ticketList1: [],
				// ticketList2: [],
				
				//三个选项被选中的索引
				activeIndex1: 0,
				activeIndex2: new Date().getDay(),
				activeIndex3: 0,
				showIndex: 0,
				//默认订票信息
				bookTicketInfo: {
					address: '博物馆区预约',
					date: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate(),
					dateTime: '9:00-12:00'
				},
			};
		},
		methods: {
			//设置屏幕高度
			setSysInfo() {
				const sysInfo = uni.getSystemInfoSync()
				const wh = sysInfo.windowHeight 
				this.sysInfo = sysInfo
				this.wh = wh
				this.ww = sysInfo.windowWidth 
				// console.log("sys: "+this.sysInfo.windowHeight)
			},
			//拿到本地时间
			getDateStr() {
				const today = new Date()
				const year = today.getFullYear()
				const month = today.getMonth() + 1
				return year + "-" + month
			},
			getDayOfWeek() {
				// console.log('this.dateList: ', this.dateList)
				const dateStr = this.getDateStr() + '-' + this.dateList[this.activeIndex2].day
				var date = new Date(dateStr)
				// console.log('dateStr: ', dateStr)
				// console.log('date: ', date)
				// console.log('今天是星期几：', date.getDay())
				return date.getDay()
			},
			//设置日期列表
			setDateList() {
				const today = new Date()
				const dayOfWeek = today.getDay()
				// console.log('datofweek ', dayOfWeek)
				const curTimestamp = today.getTime()
				for(let i = 0;i< dayOfWeek;i++) {
					const empty = {
						day: '',
						hasTicket: ''
					}
					this.dateList.push(empty)
				}
				
				for(let i = 0;i<7;i++) {
					var newDate = new Date(curTimestamp + i * 24 * 60 * 60 * 1000)
					const day = newDate.getDay()
					let dateObj = null
					if(day === 1) {
						dateObj = {
							day: newDate.getDate(),
							hasTicket: '闭馆'
						}
					}else {
						dateObj = {
							day: newDate.getDate(),
							hasTicket: '有票'
						}
					}
					this.dateList.push(dateObj)
				}
			},
			//点击选中加红色外框
			clickHandler1(i) {
				this.activeIndex1 = i
				this.showIndex = i
				this.bookTicketInfo.address = this.addressList[i].addressTitle
				this.setTicketList1()
			},
			//入馆日期被点击后的处理
			clickHandler2(i) {
				// console.log(this.ticketList1)
				if(this.dateList[i].day === '') return
				this.activeIndex2 = i
				this.bookTicketInfo.date = this.getDateStr() + '-' + this.dateList[i].day
				this.setTicketList1()
				this.getDayOfWeek()
			},
			clickHandler3(i) {
				this.activeIndex3 = i
				this.bookTicketInfo.dateTime = this.ticketList1[i].exhibitionBeginTime.split(' ')[1] + '-' + this.ticketList1[i].exhibitionEndTime.split(' ')[1]
			},
			async setTicketList1() {
				const addressTitle = this.addressList[this.activeIndex1].addressTitle
				// console.log("addressTitle: ", addressTitle)
				const date = this.getDateStr() + '-' + this.dateList[this.activeIndex2].day
				const {data: res} = await uni.$http.get(`/tickets/info?exhibitionName=${addressTitle}`+ '&date=' + date)
				// console.log("博物馆数据：", res)
				if(res.msg !== 'success') return uni.$showMsg('数据加载失败')
				this.ticketList1 = res.tickets
				// this
			},
			async setTicketList2() {
				const {data: res} = await uni.$http.get('/tickets/info?exhibitionName=康陵遗址预约')
				// console.log("博物馆数据：", res)
				if(res.msg !== 'success') return uni.$showMsg('数据加载失败')
				this.ticketList2 = res.tickets
			},
			
			//订票
			async bookTicket() {
				const visitor = JSON.parse(uni.getStorageSync('personInfo') || '{}')
				if(JSON.stringify(visitor) === '{}') {
					uni.showToast({
						icon: 'none',
						title: '请在订票前先去我的页面，填写个人实名信息'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/subpkg/person/person?type=redir'
						})
					},2000)
					return
				}
				
				// let ticketList = this.activeIndex1 === 0 ? this.ticketList1 : this.ticketList2
				
				if((new Date(this.ticketList1[this.activeIndex3].exhibitionEndTime).getTime() - new Date().getTime()) < 0) {
					return uni.showToast({
						icon: 'none',
						title: '你所选的时间段不在合法范围内',
					})
				}
				
				if(this.getDayOfWeek() === 1) {
					return uni.showToast({
						icon: 'none',
						title: '周一闭馆哦，请选择其他时间段预定吧',
					})
				}
				
				const {data: res2} = await uni.$http.get('/tickets/count/'+this.ticketList1[this.activeIndex3].ticketId)
				// console.log("剩余门票数量：", res2.ticket)
				if(res2.ticket.remainQuantity <= 0) {
					// console.log("dateList: ", this.dateList)
					// console.log("active2: ", this.activeIndex2)
					// this.dateList[this.activeIndex2].hasTicket = "无"
					return uni.showToast({
						icon: 'none',
						title: '该时间段的票已经没有了，请您预约其他时间段的门票吧'
					})
				}
				
				const ticketStorage = JSON.parse(uni.getStorageSync('myticket') || '{}') 
				if(ticketStorage && ticketStorage.expireTime === this.ticketList1[this.activeIndex3].exhibitionEndTime) {
					return uni.showToast({
						icon: 'none',
						title: '一人一个时间段只能定一张票'
					})
				}
				
				//构建订票信息
				const bookTicketInfo = {
					ticketId: this.ticketList1[this.activeIndex3].ticketId,
					visitorIdCard: JSON.parse(uni.getStorageSync('personInfo')).visitorIdCard,
					purchaseQuantity: 1,
					totalPrice: 0
				}
				
				const storageInfo = {...bookTicketInfo}
				storageInfo.expireTime = this.getDateStr() + '-' + this.dateList[this.activeIndex2].day 
				+ ' ' + this.ticketList1[this.activeIndex3].exhibitionEndTime.split(' ')[1] 
				
				// console.log("订票信息：", bookTicketInfo)
				const {data: res} = await uni.$http.post('/orders/save', bookTicketInfo)
				// console.log("res: ", res)
				if(res.msg !== 'success') {
					return uni.$showMsg('订票失败')
				}else {
					this.setTicketList1()
					//只有后台返回成功时，才缓存票的信息
					uni.setStorageSync('myticket', JSON.stringify(storageInfo))
					// this.setTicketList2()
					return uni.$showMsg('订票成功')
				}
				
			}
			
		},
		onLoad() {
			this.setSysInfo()
			this.setDateList()
			this.setTicketList1()
			// this.setTicketList2()
			
		}
		
	}
</script>

<style lang="scss">
.color-add {
	border: 1px solid #C00000;
	// background-color: #C00000;
}
.color-default {
	border: 1px solid #efefef;
}
	
.body {
	margin: 10px;
		
	.first-box {
		.address-box {
			display: flex;
		
			.address-list {
				display: flex;
				justify-content: space-around;
				align-items: center;
				flex-direction: column;
				height: 80px;
				width: 120px;
				// border: 1px solid #efefef;
				border-radius: 5px;
				margin: 5px;
				padding: 5px;
				font-size: 15px;
				
				.addressDetail {
					color: #C00000;
				}
			}
		}
	}
	.second-box {
		.dateTitle {
			
		}
		.calendar-box {
			.days-box {
				display: flex;
				justify-content: space-around;
			}
		}
		.tickets-box {
			display: flex;
			// justify-content: space-around;
			flex-wrap: wrap;
			.ticket-inner-box {
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				height: 70px;
				
				// border: 1px solid #efefef;
				border-radius: 5px;
			}
		}
	}
	.third-box {
		.time-between {
			display: flex;
		
			.time-between-list {
				display: flex;
				justify-content: space-around;
				align-items: center;
				flex-direction: column;
				height: 80px;
				width: 100px;
				// border: 1px solid #efefef;
				border-radius: 5px;
				margin: 5px 5px 0 5px; 
				padding: 5px 5px 0 5px;
				font-size: 15px;
				
				.count {
					color: #C00000;
				}
			}
		}
	}

	.commit-btn-box {
		margin: 10px 20px;
		.commit-btn {
			border-radius: 10px;
		}
	}
	
}
</style>
